package com.hsmpay.mobile.action.account;

import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.DateConvertUtil;
import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.common.util.system.Constant;
import com.hsmpay.mobile.action.trans.TransBaseAction;
import com.hsmpay.mobile.pojo.other.Settings;
import com.hsmpay.mobile.pojo.system.Holidays;
import com.hsmpay.mobile.pojo.trans.TransOrder;
import com.hsmpay.mobile.pojo.trans.TransPriorSettle;
import com.hsmpay.mobile.pojo.trans.cardcer.CardCer;
import com.hsmpay.mobile.pojo.user.UserMoney;
import com.hsmpay.mobile.service.account.CashMoneyService;
import com.hsmpay.mobile.service.other.SettingsService;
import com.hsmpay.mobile.service.other.impl.SettingsServiceImpl;
import com.hsmpay.mobile.service.system.HolidaysService;
import com.hsmpay.mobile.service.system.impl.HolidaysServiceImpl;
import com.hsmpay.mobile.service.trans.TransOrderService;
import com.hsmpay.mobile.service.trans.TransPriorSettleService;
import com.hsmpay.mobile.service.trans.cardcer.CardCerService;
import com.hsmpay.mobile.service.user.UserMoneyService;
import com.hsmpay.mobile.util.ImgFileUpload;
import com.hsmpay.mobile.pojo.organization.Organization;
import com.hsmpay.mobile.pojo.organization.OrganizationCleaning;
import com.hsmpay.mobile.service.account.OrganizationCleaningService;
import com.hsmpay.mobile.service.account.OrganizationService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

/**
 * 账务  安全提现action
 *
 * @author 颜铃璋
 * @date 2014-5-7
 */
@Controller("cashMoneySafeAction")
@Scope("prototype")
public class CashMoneySafeAction extends TransBaseAction {
    private static final long serialVersionUID = -4209437170500467527L;
    private static Logger log = Logger.getLogger(CashMoneySafeAction.class);

    @Resource(name = "cashMoneyService")
    private CashMoneyService<TransOrder, Long> cashMoneyService;
    @Resource(name = "userMoneyService")
    private UserMoneyService<UserMoney, Long> userMoneyService;
    @Resource(name = "holidaysService")
    private HolidaysService<Holidays, Long> holidaysService;
    @Resource(name = "transOrderService")
    private TransOrderService<TransOrder, Long> transOrderService;
    private TransOrder order;
    private TransPriorSettle transPriorSettle;
    @Resource(name = "transPriorSettleService")
    private TransPriorSettleService<TransPriorSettle, Long> transPriorSettleService;
    @Resource(name = "cardCerService")
    private CardCerService<CardCer, Long> cardCerService;
    @Resource(name="organizationService")
    private OrganizationService<Organization,Long> organizationService;//机构服务类
    @Resource(name = "organizationCleaningService")
    private OrganizationCleaningService<OrganizationCleaning,Long> organizationCleaningService;
    @Resource(name="settingsService")
    protected SettingsService<Settings, Long> settingsService;

    private int clientType;//客户端类型
    private long terminalTypeId;//终端类型
    private long roleId;//终端角色
    private String orderNum;//订单编号
    private Double cashMoney;//提现金额
    private Double cashMoneyFee;//提现手续费

    static double cashMoneyFeeRate = CashMoneyAction.cashMoneyFeeRate;//手续费 费率
    static double maxCashMoney = 0.0;//最大提现金额
    static double minCashMoney = 2.0;//最小提现金额
    static Double maxFeeMoney = 0.0;//封顶手续费  0 不封顶
    static Double minFeeMoney = 2.0;//最小手续费
    static double totalMaxCashMoney = 0.0;//当日最高提现金额  0 为没有限额
    static int limitNum = 0;//限制 笔数


    private File idPositive;//身份证 正面
    private File idBack;//身份证 负面
    private File cardPositive;//银行卡 正面
    private File cardBack;//银行卡 负面
    private File head;//头像
    private String bankCard;//
    private Long cardCerId;
    private Integer verifiType;
    private String codeOrPswd;

    /**
     * 提现
     *
     * @return
     * @throws Exception
     */
    public String cashMoney() throws Exception {
        log.debug("--- picUpload() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        clientType = Integer.parseInt(js.getString("clientType"));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        roleId = Long.parseLong(js.getString("roleId"));
        if (js.containsKey("functionKey"))
            functionKey = js.getString("functionKey");
        if (js.containsKey("userId"))
            userId = Long.parseLong(js.getString("userId"));
        if (js.containsKey("cashMoney"))
            cashMoney = Double.parseDouble(js.getString("cashMoney"));
        if (js.containsKey("cashMoneyFee"))
            cashMoneyFee = Double.parseDouble(js.getString("cashMoneyFee"));
        if (js.containsKey("orderNum"))
            orderNum = js.getString("orderNum");
        if (js.containsKey("cardCerId"))
            cardCerId = Long.parseLong(js.getString("cardCerId"));
        if (js.containsKey("verifiType"))
            verifiType = Integer.parseInt(js.getString("verifiType"));
        if (js.containsKey("codeOrPswd"))
            codeOrPswd = js.getString("codeOrPswd");

        functionKey = "CASHMONEY";
        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("functionKey = " + functionKey);
        log.debug("userId = " + userId);
        log.debug("cashMoney = " + cashMoney);
        log.debug("cashMoneyFee = " + cashMoneyFee);
        log.debug("orderNum = " + orderNum);
        log.debug("cardCerId = " + cardCerId);

        if (null == userId) {
            log.info("提现时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (null == cashMoney) {
            log.info("提现时, 传入参数cashMoney为空");
            sendAppErrorMsg("6001", "cashMoney");
            return null;
        }
        if (null == cashMoneyFee) {
            log.info("提现时, 传入参数cashMoneyFee为空");
            sendAppErrorMsg("6001", "cashMoneyFee");
            return null;
        }
        if (StringUtils.isBlank(functionKey)) {
            log.info("提现时, 传入参数functionKey为空");
            sendAppErrorMsg("6001", "functionKey");
            return null;
        }
        if (null != verifiType && 2 == verifiType) {
            if (StringUtils.isEmpty(codeOrPswd)) {
                log.info("提现时, 传入参数codeOrPswd为空");
                sendAppErrorMsg("6001", "codeOrPswd");
                return null;
            }
        }

        try {
            Date date = new Date();
            if (!checkTime(date)) {//检测时间
                return null;
            }

            User user = userService.getUserById(userId);

            if (!checkPIV(functionKey)) {//这块要添加根据机构判断情况
                log.warn("提现时, 银行接口暂停使用！");
                return null;
            }
            /*if(money > maxCashMoney){
				log.info("提现错误，提现金额不能大于"+maxCashMoney+" 元！");
				sendAppErrorMsg("6080", maxCashMoney+"");
				return null;
			}*/
            if (cashMoney <= minCashMoney) {
                log.info("提现错误，提现金额不能小于" + minCashMoney + " 元！");
                sendAppErrorMsg("6081", minCashMoney + "");
                return null;
            }

            if (null != user) {
                //校验支付密码
                if (null != codeOrPswd && !codeOrPswd.equals(user.getPayPassword())) {
                    log.info("提现时, 支付密码输入错误");
                    sendAppErrorMsg("6013");
                    return null;
                }

//				if(terminalTypeId == 1l || terminalTypeId == 2l || terminalTypeId == 4l){//如果是花生米  那么就暂停
//					log.warn("检查终端功能时, 该功能暂时停止使用！");
//					sendAppErrorMsg("6002");
//					return null;
//				}

                //判断 绑定银行卡
                if (null == user.getBankStatus() || 3 == user.getBankStatus()) {
                    sendAppErrorMsg("6041");
                    return null;
                } else if (2 == user.getBankStatus()) {
                    sendAppErrorMsg("6042");
                    return null;
                } else if (0 == user.getBankStatus()) {//0:认证失败 1:认证通过 2:审核中 3:未申请认证 DEFAULT 3
                    sendAppErrorMsg("6043");
                    return null;
                }

                //判断用户 结算状态
                if (user.getClearStatus() == null || user.getClearStatus().intValue() != 1) {
                    String message = encryptAppMsg(0, "UCLS", "用户存在违法，请跟管理员联系！");
                    sendAppMsg(message);
                    return null;
                }

                //查询订单
                order = new TransOrder();
                order.setOrderNum(orderNum);
                order = transOrderService.searchEntity(order);
                transPriorSettle = new TransPriorSettle();
                transPriorSettle.setOrderNum(orderNum);
                transPriorSettle = transPriorSettleService.searchEntity(transPriorSettle);
                if (null == order) {//不存在该订单
                    log.warn("安全提现时, 不存在该订单！");
                    sendAppErrorMsg("6086");
                    return null;
                }
                if (1 != order.getOrderTypeId().intValue()) {//订单不是收款订单
                    log.warn("安全提现时, 订单不是收款订单！");
                    sendAppErrorMsg("6087");
                    return null;
                }
                if (1 != order.getStatus().intValue()) {//收款订单不是交易成功的订单
                    log.warn("提现失败，收款订单不是交易成功的订单！");
                    sendAppErrorMsg("6092");
                    return null;
                }

                double chargeAmount = order.getChargeAmount();
                if (chargeAmount != NumberUtil.roundF2((cashMoneyFee + cashMoney)) && chargeAmount != cashMoney) {//金额不相等
                    log.warn("安全提现时, 传入提现金额与手续费不符！");
                    sendAppErrorMsg("6088");
                    return null;
                }
                if (!checkOrderTime(order.getCreateDate())) {
                    String dateStr = DateConvertUtil.dateString(order.getCreateDate());
                    log.warn("提现失败, 该订单只能在 " + dateStr + " 22:40:00 前执行提现，对于不能提现的交易，请等待T+1结算！");
                    sendAppErrorMsg("6090");
                    return null;
                }
                if (null != order.getCashOrderNum()) {
                    TransOrder cashOrder = new TransOrder();
                    cashOrder.setOrderNum(order.getCashOrderNum());
                    cashOrder = transOrderService.searchEntity(cashOrder);
                    if (null == cashOrder || cashOrder.getStatus().intValue() != 0) {
                        log.warn("安全提现失败，不允许重复提现！");
                        sendAppErrorMsg("6091");
                        return null;
                    }
                }

                //判断  收款时  付款卡号是否  认证
                int isCardCer = cardCerService.getCardCerStatusByBankCard(order.getBankCard(), 1);//0 代表认证失败 1 认证成功 2 未审核  3 未认证
                Integer channelId = transPriorSettle.getCollectionType();
                if(channelId != 34){//瑞晟
                    if (isCardCer != 1 && null == cardCerId) {//请
                        log.warn("提现错误，请上传收款时，付款卡号凭证信息！");
                        sendAppErrorMsg("6089");
                    }
                }

                //金额是否足够
                boolean isZhugou = userMoneyService.moneyTheAdequacy(userId, chargeAmount, 1);
                if (!isZhugou) {
                    log.info("提现错误，金额不足！");
                    sendAppErrorMsg("6082", chargeAmount + "");
                    return null;
                }

                //Date date = new Date();
                TransOrder transOrder = new TransOrder();
                transOrder.setOrderNum(getOrderNumByDate(date));
                transOrder.setOrderTypeId(8l);//提现
                transOrder.setUserId(userId);
                transOrder.setTransMoney(chargeAmount);

                transOrder.setFeeMoney(cashMoneyFee);//fee);//手续费
                transOrder.setBrokerage(0.0000);//brokerage);
                transOrder.setDealerBrokerage(0.0000);
                transOrder.setChargeAmount(cashMoney);
                transOrder.setRootCategory("账务管理");
                transOrder.setCategory("提现");
                //transOrder.setName();//user.getUserName());//付款方
                transOrder.setBankCard(order.getBankCard());//收款 订单的  付款卡号 ####################################
                //transOrder.setOpeningBank(user.getOpeningBank());//"农业银行");//);
                transOrder.setObjectiveName(user.getCardholder());//对方姓名
                transOrder.setObjectiveCard(user.getBankCard());//对方银行卡
                transOrder.setObjectiveOpBank(user.getOpeningBank());//对方银行

                transOrder.setStatus(2);
                if(channelId != 34 && isCardCer != 1){
                    transOrder.setStatus(9);//交易状态  0交易失败 1交易成功 2银行交易处理中 3 未付款 4等待对方付款5关闭交易  9 未审核
                }

                transOrder.setClearing(0);//结算状态 0未结算 1结算
                transOrder.setDescription("系统结算");//交易详情
                transOrder.setCreateDate(date);
                transOrder.setUpdateLongTime(date.getTime());

                //transOrder.setBranchesBank(cashMoney.getBranchesBank());//用户银行支行
                //transOrder.setBBankProvince(cashMoney.getBBankProvince());
                //transOrder.setBBankCity(cashMoney.getBBankCity());
                //transOrder.setMobile(cashMoney.getMobile());//用户 手机号
                transOrder.setObjectiveBBank(user.getBranchesBank());//对方。银行支行
                transOrder.setObjectiveBBProvince(user.getBBankProvince());
                transOrder.setObjectiveBBCity(user.getBBankCity());
                transOrder.setObjectiveMobile(user.getMobile());//对方手机号
                transOrder.setObjectiveBBankCode(user.getBranchesBankCode());
                //三毛接口 银行代码  鉴权
                transOrder.setObjectiveAccBankCode(user.getAccBankCode());
                transOrder.setTerminalTypeId(terminalTypeId);
                transOrder.setRoleId(roleId);
                transOrder.setOrgOrderNum(order.getOrderNum());//原订单编号
                transOrder.setSignaturePath(order.getSignaturePath());//获得收款 签名
                double cashRate=0.002;
                //判断时间是否是周六\日 或者 是节假日并且不是法定工作日
                if ((holidaysService.isWeekend(date) || holidaysService.isHolidays(date))
                        && !holidaysService.isLegalWorkDay(date)) {

                    Settings settings= settingsService.getSettingsByFk("SPECIAL_RATES_AND_FEES");//获取周六\日T+0提现额外手续费率
                    cashRate += Double.parseDouble(settings.getMainValue());//加上周六\日额外手续率
                }
                transOrder.setFeeRate(user.getCashRate() < cashRate ? cashRate : user.getCashRate());//订单费率
                transOrder.setFdMaxFee(0.00);//用户封顶最高
                transOrder.setFdMinFee(2.00);//用户封顶最低
                transOrder.setClientType(clientType);

                //修改原订单
                transOrderService.updateCashOrderByNum(order.getOrderNum(), transOrder.getOrderNum());

                //判断 机构预存款
                int flag = cashMoneyService.cashMoneySafe(transOrder, cardCerId);

                if (flag == 1) {
                    String reqMsg = "提现成功，一小时内自动结算到您绑定的银行卡账号中！";
                    if (transOrder.getStatus().intValue() == 9) {
                        reqMsg = "提现成功，请等待审核卡号认证，认证后一小时内自动结算到您绑定的银行卡账号中！";
                    }

                    Map<String, Object> result = new LinkedHashMap<String, Object>();
                    result.put("reqCode", "0000");
                    result.put("reqMsg", reqMsg);
                    sendAppMsg(result);
                } else if (flag == 2) {//预存款不足
                    //修改原订单
                    transOrderService.updateCashOrderByNum(order.getOrderNum(), "");
                    sendAppErrorMsg("6084");
                }
            } else {
                log.warn("提现时, 用户Id=" + userId + " 对应的用户不存在!");
                sendAppErrorMsg("6012", userId + "");
            }
        } catch (Exception e) {
            //修改原订单
            transOrderService.updateCashOrderByNum(order.getOrderNum(), "");
            e.printStackTrace();
            throw e;
        }
        return null;
    }

    /**
     * 提现检测
     *
     * @return
     * @throws Exception
     */
    public String checkCashMoney() throws Exception {
        log.debug("--- checkCashMoney() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        clientType = Integer.parseInt(js.getString("clientType"));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        roleId = Long.parseLong(js.getString("roleId"));

        if (js.containsKey("userId"))
            userId = Long.parseLong(js.getString("userId"));
        if (js.containsKey("orderNum"))
            orderNum = js.getString("orderNum");
        functionKey = "CASHMONEY";

        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("userId = " + userId);
        log.debug("functionKey = " + functionKey);
        log.debug("orderNum = " + orderNum);
        if (null == userId) {
            log.info("提现时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (StringUtils.isBlank(functionKey)) {
            log.info("提现时, 传入参数functionKey为空");
            sendAppErrorMsg("6001", "functionKey");
            return null;
        }
        if (StringUtils.isBlank(orderNum)) {
            log.info("提现时, 传入参数orderNum为空");
            sendAppErrorMsg("6001", "orderNum");
            return null;
        }

        try {
            Date date = new Date();
            if (!checkTime(date)) {//检测时间
                return null;
            }
            User user = userService.getUserById(userId);

            if (!checkPIV(functionKey)) {
                log.warn("提现时, 银行接口暂停使用！");
                return null;
            }

//			//判断 用户提现限制
//			boolean isLimit = transLimitService.cashMoneyNumberLimit(userId, limitNum);
//			if(isLimit){
//				log.info("提现错误，提现次数达到上限!");
//				sendAppErrorMsg("6083");
//				return null;
//			}

            if (null != user) {

                //判断用户 结算状态
                if (user.getClearStatus() == null || user.getClearStatus().intValue() != 1) {
                    String message = encryptAppMsg(0, "UCLS", "用户存在违法，请跟管理员联系！");
                    sendAppMsg(message);
                    return null;
                }

                //查询订单
                order = new TransOrder();
                order.setOrderNum(orderNum);
                order = transOrderService.searchEntity(order);
                transPriorSettle = new TransPriorSettle();
                transPriorSettle.setOrderNum(orderNum);
                transPriorSettle = transPriorSettleService.searchEntity(transPriorSettle);
                if (null == order) {//不存在该订单
                    log.warn("安全提现时, 不存在该订单！");
                    sendAppErrorMsg("6086");
                    return null;
                }
                if (null != order.getOrderTypeId() && 11l == order.getOrderTypeId()){
                    log.warn("零费率订单" + orderNum + "不允许提现");
                    sendAppErrorMsg("6111");
                    return null;
                }
                if (1 != order.getOrderTypeId().intValue()) {//订单不是收款订单
                    log.warn("安全提现时, 订单不是收款订单！");
                    sendAppErrorMsg("6087");
                    return null;
                }
                if (!checkOrderTime(order.getCreateDate())) {
                    String dateStr = DateConvertUtil.dateString(order.getCreateDate());
                    log.warn("提现失败, 该订单只能在 " + dateStr + " 22:40:00 前执行提现，对于不能提现的交易，请等待T+1结算！");
                    sendAppErrorMsg("6090");
                    return null;
                }
                if (null != order.getCashOrderNum()) {
                    TransOrder cashOrder = new TransOrder();
                    cashOrder.setOrderNum(order.getCashOrderNum());
                    cashOrder = transOrderService.searchEntity(cashOrder);
                    if (null != cashOrder && cashOrder.getStatus().intValue() != 0) {
                        log.warn("安全提现失败，不允许重复提现！");
                        sendAppErrorMsg("6091");
                        return null;
                    }
                }

                bankCard = order.getBankCard();
                //查询数据库  看看该 银行卡  有没有认证通过
                int isCardCer = cardCerService.getCardCerStatusByBankCard(bankCard, 1);//0 代表认证失败 1 认证成功 2 认证处理中  3 未认证
                Integer channelId = transPriorSettle.getCollectionType();
                double transMoney = order.getTransMoney();
                double feeMoney = order.getFeeMoney();
                double chargeAmount = order.getChargeAmount();
                double cashMoneyFee = getFee(chargeAmount, user.getCashRate());//提现手续费
                double cashMoney = NumberUtil.roundF2((chargeAmount - cashMoneyFee));//NumberUtil.numFormatToNum((chargeAmount*(1-cashMoneyFeeRate)));
                if (cashMoney <= minCashMoney) {
                    log.info("提现错误，提现金额不能小于" + minCashMoney + " 元！");
                    sendAppErrorMsg("6081", minCashMoney + "");
                    return null;
                }

                //工作日开始时间与结束时间
                Settings settings=new Settings();
                //工作日说明与标题
                Settings settings1=new Settings();
                //周六日节假日费率与手续费
                Settings settings2=new Settings();
                settings=settingsService.getSettingsByFk("NORMAL_START_AND_ENDTIME");
                settings1=settingsService.getSettingsByFk("NORMAL_INSTRUCTIONS_AND_TITLE");
                settings2=settingsService.getSettingsByFk("SPECIAL_RATES_AND_FEES");
                String reqMsg=settings1.getMainValue();
                //是否是工作日 包括法定工作日
                boolean worKing = true;
                Map<String, Object> result = new LinkedHashMap<String, Object>();
                //周六日\节假日 T+0提现开关设置
                String switchSettings = settingsService.getMainValueByFk("SPECIAL_SETUP");
                String startAndEndTime = settings.getMainValue()+":00 ~ "+settings.getValue2()+":00";
                reqMsg = reqMsg.replaceAll("\\$param", startAndEndTime);
                //判断时间是否是周六\日  或者 是节假日并且不是法定工作日
                if ((holidaysService.isWeekend(date) || holidaysService.isHolidays(date))
                        && !holidaysService.isLegalWorkDay(date)
                        && switchSettings.equals("TRUE")) {
                    if(user.getClearRate() != null&&user.getClearRate()!=0.0){
                        user.setCashRate(user.getCashRate()+ Double.parseDouble(settings2.getMainValue()));//加上周六\日额外手续费率
                    }
                    //获取周六日、节假日 提现开始与结束时间
                    settings=settingsService.getSettingsByFk("SPECIAL_START_AND_ENDTIME");
                    //周六日 T+0 提现说明与标题
                    settings1 = settingsService.getSettingsByFk("SPECIAL_INSTRUCTIONS_AND_TITLE");
                    reqMsg = settings1.getMainValue();
                    startAndEndTime = settings.getMainValue()+":00 ~ "+settings.getValue2()+":00";
                    reqMsg = reqMsg.replaceAll("\\$param", startAndEndTime);
                    worKing=false;
                }
                if(channelId != 34){
                    result.put("isCardCer", isCardCer);//收款时付款的那个银行卡 认证状态   只要不等于1  就需要认证
                }else {
                    result.put("isCardCer", 1);//收款时付款的那个银行卡 认证状态   只要不等于1  就需要认证
                }

                result.put("bankCard", bankCard);//收款时付款的那个银行卡
                result.put("cashMoneyFeeRate", (null == user.getCashRate() ? cashMoneyFeeRate : user.getCashRate()));//提现手续费费率
                result.put("cashMoney", cashMoney);//提现金额
                result.put("cashMoneyFee", cashMoneyFee);//提现手续费
                result.put("transMoney", transMoney);//收款交易金额
                result.put("feeMoney", feeMoney);//收款交易手续费
                result.put("reqCode", "0000");
                result.put("reqMsg", reqMsg);//T+0提现说明
                result.put("title",settings1.getValue2());//T+0提现标题
                result.put("worKing",worKing);//是否是工作日 包括法定工作日 true/false
                sendAppMsg(result);

            } else {
                log.warn("提现时, 用户Id=" + userId + " 对应的用户不存在!");
                sendAppErrorMsg("6012", userId + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return null;
    }

    //计算 提现手续费
    private double getFee(Double chargeAmount, Double cashRate) throws Exception {
		/*Double cashMoney = chargeAmount / (1 + cashMoneyFeeRate);
		Double fee = chargeAmount - NumberUtil.numFormatToNum(cashMoney);*/
        Double fee = 0.00;
        if (cashRate < 0.002) cashRate = 0.002;
        Date date=new Date();
        Settings settings=new Settings();
        //周六日\节假日 T+0提现开关设置
        String switchSettings=settingsService.getMainValueByFk("SPECIAL_SETUP");
        //获取周六\日T+0提现额外手续费率与手续费
        settings = settingsService.getSettingsByFk("SPECIAL_RATES_AND_FEES");
        //判断时间是否是周六\日 或者 是节假日并且不是法定工作日
        if ((holidaysService.isWeekend(date) || holidaysService.isHolidays(date))
                 && !holidaysService.isLegalWorkDay(date)
                 && switchSettings.equals("TRUE")) {
            //加上周六\日额外手续费率
            cashRate += Double.parseDouble(settings.getMainValue());
        }
        if (null != cashRate) fee = NumberUtil.roundF2(chargeAmount * cashRate);
        if (fee < minFeeMoney) {
            fee = minFeeMoney;
            //当手续费小于2元,是周六\日 或者是节假日并且不是法定工作日 就追加额外手续费
            //判断时间是否是周六\日 或者 节假日并且不是法定工作日
            if ((holidaysService.isWeekend(date) || holidaysService.isHolidays(date))
                    && !holidaysService.isLegalWorkDay(date)
                    && switchSettings.equals("TRUE")) {
                fee += Double.parseDouble(settings.getValue2());//加上周六\日额外手续费
            }
        }
        if (maxFeeMoney != 0.0 && fee > maxFeeMoney) {
            fee = maxFeeMoney;
        }
        return fee;
    }
    /**
     * 检测时间
     *
     * @return
     * @throws Exception
     */
    private boolean checkTime(Date date) throws Exception {
        //工作日 T+0 开始时间 与 结束时间
        Settings workDayT0Time = settingsService.getSettingsByFk("NORMAL_START_AND_ENDTIME");
        //节假日 T+0 是否可以提现
        String holidayT0 = settingsService.getMainValueByFk("SPECIAL_SETUP");
        boolean isT0 = false;
        if(holidayT0.equals("TRUE")){
            isT0 = true;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        //是否为节假日
        boolean isHoliday = holidaysService.isRealHolidays(date);

        //节假日  t0开放
        if (isHoliday && isT0) {
            Settings holidayT0Time = settingsService.getSettingsByFk("SPECIAL_START_AND_ENDTIME");
            if (cal.get(Calendar.HOUR_OF_DAY) < Integer.parseInt(holidayT0Time.getMainValue()) || cal.get(Calendar.HOUR_OF_DAY) >= Integer.parseInt(holidayT0Time.getValue2())) {
                String message = encryptAppMsg(0, "LS03", "尊敬的用户您好，节假日提现功能功能时间只在节假日的" + holidayT0Time.getMainValue() + ":00 —— " + holidayT0Time.getValue2() + ":00 时间内提供服务！");
                sendAppMsg(message);
                return false;
            }
        }
        //节假日  t0不开放
        if (isHoliday && !isT0) {
            String message = encryptAppMsg(0, "LS02", "尊敬的用户您好，提现功能只在工作日的" + workDayT0Time.getMainValue() + ":00 —— " + workDayT0Time.getValue2() + ":00 时间内提供服务！");
            sendAppMsg(message);
            return false;
        }
        if (!isHoliday) {
            if (cal.get(Calendar.HOUR_OF_DAY) < Integer.parseInt(workDayT0Time.getMainValue()) || cal.get(Calendar.HOUR_OF_DAY) >= Integer.parseInt(workDayT0Time.getValue2())) {
                String message = encryptAppMsg(0, "LS01", "尊敬的用户您好，提现功能只在工作日的"+workDayT0Time.getMainValue()+":00 —— "+workDayT0Time.getValue2()+":00 时间内提供服务！");
                sendAppMsg(message);
                return false;
            }
        }
        return true;
    }

    /**
     * 检查订单时间是否可以提现
     *
     * @param orderDate
     * @return
     * @throws Exception
     */
    private boolean checkOrderTime(Date orderDate) throws Exception {
        Date tempDate = DateConvertUtil.getSpecifiedDayBefore(order.getCreateDate());
        Date startDate = DateConvertUtil.stringDateTime(DateConvertUtil.dateString(tempDate) + " 23:00:00");//昨天 23：00：00
        Date stopDate = DateConvertUtil.stringDateTime(DateConvertUtil.dateString(orderDate) + " 22:40:00");//今天 22：40：00

        Date date = new Date();

        if (date.getTime() < startDate.getTime()) {
            return false;
        } else if (date.getTime() > stopDate.getTime()) {
            return false;
        }
        return true;
    }

    /**
     * 上传银行卡认证
     *
     * @return
     * @throws Exception
     */
    public String uploadCardCerd() throws Exception {
        log.debug("--- checkCashMoney() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        clientType = Integer.parseInt(js.getString("clientType"));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        roleId = Long.parseLong(js.getString("roleId"));

        functionKey = "CASHMONEY";
        if (js.containsKey("userId"))
            userId = Long.parseLong(js.getString("userId"));
        if (js.containsKey("bankCard"))
            bankCard = js.getString("bankCard");
        if (js.containsKey("orderNum"))
            orderNum = js.getString("orderNum");
        if (js.containsKey("idPositive")) {
            String idPositiveStr = js.getString("idPositive");
            File file = new File(getRealPath("/images") + File.separator + "temp");
            if(!file.exists()){
                file.mkdir();
            }
            String relPath = getRealPath("/images") + File.separator + "temp" + File.separator + DateConvertUtil.dateString(new Date(), "yyyyMMddhhmmssSSS") + ".jpg";
            idPositive = ImgFileUpload.getPicByBase64Str(relPath, idPositiveStr);
        }
        if (js.containsKey("idBack")) {
            String idBackStr = js.getString("idBack");
            String relPath = getRealPath("/images") + File.separator + "temp" + File.separator + DateConvertUtil.dateString(new Date(), "yyyyMMddhhmmssSSS") + ".jpg";
            idBack = ImgFileUpload.getPicByBase64Str(relPath, idBackStr);
        }
        if (js.containsKey("cardPositive")) {
            String cardPositiveStr = js.getString("cardPositive");
            String relPath = getRealPath("/images") + File.separator + "temp" + File.separator + DateConvertUtil.dateString(new Date(), "yyyyMMddhhmmssSSS") + ".jpg";
            cardPositive = ImgFileUpload.getPicByBase64Str(relPath, cardPositiveStr);
        }
        if (js.containsKey("cardBack")) {
            String cardBackStr = js.getString("cardBack");
            String relPath = getRealPath("/images") + File.separator + "temp" + File.separator + DateConvertUtil.dateString(new Date(), "yyyyMMddhhmmssSSS") + ".jpg";
            cardBack = ImgFileUpload.getPicByBase64Str(relPath, cardBackStr);

        }
        if (js.containsKey("head")) {
            String headStr = js.getString("head");
            String relPath = getRealPath("/images") + File.separator + "temp" + File.separator + DateConvertUtil.dateString(new Date(), "yyyyMMddhhmmssSSS") + ".jpg";
            head = ImgFileUpload.getPicByBase64Str(relPath, headStr);
        }
        //log.debug("cardCerId = " + js.getString("cardCerId"));
        if (js.containsKey("cardCerId") && StringUtils.isNotBlank(js.getString("cardCerId")))
            cardCerId = Long.parseLong(js.getString("cardCerId"));


        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("userId = " + userId);
        log.debug("functionKey = " + functionKey);
        log.debug("orderNum = " + orderNum);
        log.debug("cardCerId = " + cardCerId);
        if (null == userId) {
            log.info("提现时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (StringUtils.isBlank(functionKey)) {
            log.info("提现时, 传入参数functionKey为空");
            sendAppErrorMsg("6001", "functionKey");
            return null;
        }
        if (StringUtils.isBlank(orderNum)) {
            log.info("提现时, 传入参数orderNum为空");
            sendAppErrorMsg("6001", "orderNum");
            return null;
        }
        if (null == idPositive && null == idBack && null == cardPositive
                && null == cardBack && null == head) {
            log.info("提现时, 传入参数idPositive为空");
            sendAppErrorMsg("6001", "idPositive idBack cardPositive cardBack head");
            return null;
        }

        try {
            //查询订单
            order = new TransOrder();
            order.setOrderNum(orderNum);
            order = transOrderService.searchEntity(order);
            TransPriorSettle transPriorSettle = new TransPriorSettle();
            transPriorSettle.setOrderNum(orderNum);
            transPriorSettle = transPriorSettleService.searchEntity(transPriorSettle);
            if (null == order || null == transPriorSettle) {//不存在该订单
                log.warn("安全提现时, 不存在该订单！");
                sendAppErrorMsg("6086");
                return null;
            }
            if (1 != order.getOrderTypeId().intValue()) {//订单不是收款订单
                log.warn("安全提现时, 订单不是收款订单！");
                sendAppErrorMsg("6087");
                return null;
            }

            int isCardCer = cardCerService.getCardCerStatusByBankCard(order.getBankCard(), 1);//0 代表认证失败 1 认证成功 2 认证处理中  3 未认证
            if (isCardCer == 1) {
                log.warn("安全提现时, 卡号已经通过认证，不需要再传认证图片了！");
                sendAppErrorMsg("6092");
                return null;
            }

            CardCer cardCer = new CardCer();
            if (null != cardCerId) {
                cardCer.setId(cardCerId);
                cardCer.setVerifiType(1);//提现
                cardCer = cardCerService.searchEntity(cardCer);//根据ID 查询认证信息
                if (null == cardCer) {
                    sendAppErrorMsg("9999");
                }
            }
            cardCer.setBankCard(order.getBankCard());//


            String dPIUrl = Constant.getAttribute("SERVER_CARDCER_URL");
            StringBuilder sb = new StringBuilder();
            String dirDateStr = DateConvertUtil.dateString(new Date());
            String baseRPath = ImgFileUpload.mkDirectory(sb.append(getRealPath(dPIUrl)).append(File.separator).append(dirDateStr).toString());
            String fileType = ".jpg";//ImgFileUpload.getFileType(idPositiveFileName);
            String dateStr = "";
            String filePath = "";
            String idPositiveUrl = "";

            //证件正面
            if (null != idPositive) {
                log.debug("上传身份证证件正面");
                dateStr = DateConvertUtil.dateString(new Date(), "hhmmssSSS");
                sb = new StringBuilder();
                filePath = sb.append(baseRPath).append(File.separator).append(dateStr).append(fileType).toString();
                sb = new StringBuilder();
                idPositiveUrl = sb.append(dPIUrl).append(dirDateStr).append("/").append(dateStr).append(fileType).toString();
                ImgFileUpload.uploadAndThumd(filePath, idPositive, 80, 80, terminalTypeId);
                cardCer.setIdPositivePath(idPositiveUrl);//证件正面
            }
            //证件背面
            if (null != idBack) {
                log.debug("上传身份证证件背面");
                dateStr = DateConvertUtil.dateString(new Date(), "hhmmssSSS");
                sb = new StringBuilder();
                filePath = sb.append(baseRPath).append(File.separator).append(dateStr).append(fileType).toString();
                sb = new StringBuilder();
                String idBackUrl = sb.append(dPIUrl).append(dirDateStr).append("/").append(dateStr).append(fileType).toString();
                ImgFileUpload.uploadAndThumd(filePath, idBack, 80, 80, terminalTypeId);
                cardCer.setIdBackPath(idBackUrl);//证件背面
            }
            //卡号正面
            if (null != cardPositive) {
                log.debug("上传卡号正面");
                dateStr = DateConvertUtil.dateString(new Date(), "hhmmssSSS");
                sb = new StringBuilder();
                filePath = sb.append(baseRPath).append(File.separator).append(dateStr).append(fileType).toString();
                sb = new StringBuilder();
                String cardPositiveUrl = sb.append(dPIUrl).append(dirDateStr).append("/").append(dateStr).append(fileType).toString();
                ImgFileUpload.uploadAndThumd(filePath, cardPositive, 80, 80, terminalTypeId);
                cardCer.setCardPositivePath(cardPositiveUrl);//卡号正面
            }
            //卡号背面
            if (null != cardBack) {
                log.debug("上传卡号背面");
                dateStr = DateConvertUtil.dateString(new Date(), "hhmmssSSS");
                sb = new StringBuilder();
                filePath = sb.append(baseRPath).append(File.separator).append(dateStr).append(fileType).toString();
                sb = new StringBuilder();
                String cardBackUrl = sb.append(dPIUrl).append(dirDateStr).append("/").append(dateStr).append(fileType).toString();
                ImgFileUpload.uploadAndThumd(filePath, cardBack, 80, 80, terminalTypeId);
                cardCer.setCardBackPath(cardBackUrl);//卡号背面
            }
            //头像
            if (null != head) {
                log.debug("上传卡号头像");
                dateStr = DateConvertUtil.dateString(new Date(), "hhmmssSSS");
                sb = new StringBuilder();
                filePath = sb.append(baseRPath).append(File.separator).append(dateStr).append(fileType).toString();
                sb = new StringBuilder();
                String headUrl = sb.append(dPIUrl).append(dirDateStr).append("/").append(dateStr).append(fileType).toString();
                ImgFileUpload.uploadAndThumd(filePath, head, 80, 80, terminalTypeId);
                cardCer.setHeadPath(headUrl);//头像
            }

            cardCer.setIssueBank(transPriorSettle.getIssueBank());//发卡行
            cardCer.setCardType(transPriorSettle.getCardType());//卡类型
            cardCer.setExpireDate(transPriorSettle.getExpireDate());//有效期
            cardCer.setStatus(3);//未审核
            cardCer.setCreateDate(new Date());
            cardCer.setUserId(userId);
            cardCer.setVerifiType(1);//提现审核
            cardCerId = cardCerService.insertOrUpdateCardCer(cardCer);

            //根据 卡号  查询 bankCard  认证状态
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            result.put("reqCode", "0000");
            result.put("reqMsg", "上传银行卡认证成功！");
            result.put("cardCerId", cardCerId);
            sendAppMsg(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- uploadCardCerd() end ---");
            if (null != idPositive)
                idPositive.delete();
            if (null != idBack)
                idBack.delete();
            if (null != cardPositive)
                cardPositive.delete();
            if (null != cardBack)
                cardBack.delete();
            if (null != head)
                head.delete();
        }
        return null;
    }


    public static void main(String args[]) {
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        log.debug(cal.get(Calendar.HOUR_OF_DAY));
    }
}
